/*不是angular的服务*/
var baseService = function($http,$q,baseUrl,name,mapping) {
    this.$http = $http;
    this.$q = $q;
    this.baseUrl = baseUrl;
    this.name = name;
    this.mapping = mapping;
}

//将前端的数据转化为后台
//数据,mapping映射
baseService.prototype.columnToData=function(data,mapping) {
    //var a = {uname:""}
    var obj = {};
    for(var key in data) {
        if(mapping[key]==undefined){
            continue;
        }
        //如果mapping[key]是undefined 自己过滤
        obj[mapping[key]] = data[key];
    }
    return obj;
}
//将后台的数据转化为前台
baseService.prototype.dataToColumn = function(data,mapping) {
    var obj = {};
    //mapping  {uname:"name" ,  upass:'pass'}
    //data  {name:""}
    for(var key in mapping) {
        //key  uname
        obj[key] = data[mapping[key]];
    }
    return obj;
}

baseService.prototype.add = function(obj) {
    var that= this;
    obj = that.columnToData(obj,that.mapping[that.name]);
    var q = that.$q.defer();
    that.$http.post(that.baseUrl+'/'+that.name+'/insert',obj).then(function(e) {
        q.resolve(e.data);
    },function(err) {
        q.reject(err)
    });
    return q.promise;
}

baseService.prototype.delete = function(obj) {
	//console.info(obj)
    var that= this;
    var q = that.$q.defer();
    that.$http.post(that.baseUrl,jQuery.param(obj)).then(function(e) {
        q.resolve(e.data);
    },function(err) {
        q.reject(err)
    });
    return q.promise;
}
//单独post
baseService.prototype.oPost = function(obj) {
	//console.info(obj)
    var that= this;
    var q = that.$q.defer();
    that.$http({  
	   method:'post',  
	   url:that.baseUrl,  
	   data:obj,  
	   headers:{'Content-Type': 'application/json'},  
	 
	}).then(function(e) {
        q.resolve(e.data);
    },function(err) {
        q.reject(err)
    });
    return q.promise;  
//  that.$http.post(that.baseUrl,jQuery.param(obj)).then(function(e) {
//      q.resolve(e.data);
//  },function(err) {
//      q.reject(err)
//  });
//  return q.promise;
}

baseService.prototype.list = function(obj) {
    var that = this;
    var q = that.$q.defer();
     //that.$http.get(that.baseUrl+'/'+that.name+'/list',{params:obj}).then(function(e) {
     	that.$http.get(that.baseUrl,{params:obj}).then(function(e) {
         q.resolve(e.data);
     },function(err) {
         q.reject(err)
     });
    return q.promise;
}

//===================//
baseService.prototype.login = function(obj) {
	//console.info(obj)
    var that= this;
    var q = that.$q.defer();
     that.$http({
			method: 'POST',
			url: that.baseUrl,
			params: obj
		}).success(function(data){
			 q.resolve(data);
			
		}).error(function(data){
			
			q.reject(data)
			
		})
		return q.promise;
}
